#include<opencv2/opencv.hpp>
#include <cv.h>
#include <highgui.h>
#include<iostream>
using namespace std;
using namespace cv;





void Initialize(CvMat* pFrameMat);
void update(CvMat* pFrameMat,CvMat* segMat);

int main(int argc, char* argv[]){
	IplImage* pFrame=NULL;
	cvNamedWindow("video",1);
	CvCapture* pCapture=NULL;
	if(argc==1 ||(argc==2 && strlen(argv[1])==1 && isdigit(argv[1][0])))
		pCapture=cvCaptureFromCAM(argc==2?argv[1][0]-'0':0);
	else if(argc==2)
		pCapture=cvCaptureFromAVI(argv[1]);
	if(!pCapture)
	{
		  fprintf(stderr,"Could not initialize capturing...\n");
	}
	 
	int nFrame=1;
	IplImage* segMap,*pAfter;
	CvMat* segMat,*pAfterMat;
	while(pFrame=cvQueryFrame(pCapture))
	{
		 cvShowImage("video1",pFrame);
		segMap=cvCreateImage(cvSize(pFrame->width,pFrame->height),IPL_DEPTH_8U,1);
		segMat=cvCreateMat(pFrame->height,pFrame->width,CV_32FC1);
		 if(nFrame==1){
			 pAfter=cvCreateImage(cvSize(pFrame->width,pFrame->height),IPL_DEPTH_8U,1);
			 pAfterMat=cvCreateMat(pFrame->height,pFrame->width,CV_32FC1);

			 cvCvtColor(pFrame,pAfter,CV_BGR2GRAY);
			 cvConvert(pAfter,pAfterMat);
			 Initialize(pAfterMat);

		 }
		 else{
			 
			 cvCvtColor(pFrame,pAfter,CV_BGR2GRAY);
			 cvConvert(pAfter,pAfterMat);
			 update(pAfterMat,segMat);
			 cvConvert(segMat,segMap);

			
			 cvShowImage("video2",segMap);

		 }
		 nFrame++;

		  
		  if(cvWaitKey(2)>=0) break;
	}
	return 0;
}